package org.jeecg.modules.oms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.oms.entity.SemiProductSalesOrderTransaction;
import org.jeecg.modules.oms.service.ISemiProductSalesOrderTransactionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.apache.shiro.SecurityUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.List;

/**
 * 半成品销售订单交易记录Controller
 */
@Api(tags = "半成品销售订单交易记录管理")
@RestController
@RequestMapping("/oms/semiProductSalesOrderTransaction")
@Slf4j
public class SemiProductSalesOrderTransactionController extends JeecgController<SemiProductSalesOrderTransaction, ISemiProductSalesOrderTransactionService> {

    @Autowired
    private ISemiProductSalesOrderTransactionService transactionService;

    /**
     * 分页列表查询
     */
    @AutoLog(value = "半成品销售订单交易记录-分页列表查询")
    @ApiOperation(value = "半成品销售订单交易记录-分页列表查询", notes = "半成品销售订单交易记录-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<SemiProductSalesOrderTransaction>> queryPageList(SemiProductSalesOrderTransaction transaction,
                                                                         @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                         HttpServletRequest req) {
        QueryWrapper<SemiProductSalesOrderTransaction> queryWrapper = QueryGenerator.initQueryWrapper(transaction, req.getParameterMap());
        queryWrapper.orderByDesc("transaction_time");
        
        Page<SemiProductSalesOrderTransaction> page = new Page<SemiProductSalesOrderTransaction>(pageNo, pageSize);
        IPage<SemiProductSalesOrderTransaction> pageList = transactionService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 根据订单ID查询交易记录
     */
    @AutoLog(value = "半成品销售订单交易记录-根据订单ID查询")
    @ApiOperation(value = "半成品销售订单交易记录-根据订单ID查询", notes = "半成品销售订单交易记录-根据订单ID查询")
    @GetMapping(value = "/getByOrderId")
    public Result<List<SemiProductSalesOrderTransaction>> getByOrderId(@RequestParam(name = "orderId", required = true) String orderId) {
        try {
            List<SemiProductSalesOrderTransaction> transactions = transactionService.getByOrderId(orderId);
            return Result.OK(transactions);
        } catch (Exception e) {
            log.error("根据订单ID查询交易记录失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 添加交易记录
     */
    @AutoLog(value = "半成品销售订单交易记录-添加")
    @ApiOperation(value = "半成品销售订单交易记录-添加", notes = "半成品销售订单交易记录-添加")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody SemiProductSalesOrderTransaction transaction) {
        try {
            boolean result = transactionService.addTransaction(transaction);
            if (result) {
                return Result.OK("添加成功！");
            } else {
                return Result.error("添加失败！");
            }
        } catch (Exception e) {
            log.error("添加交易记录失败", e);
            return Result.error("添加失败：" + e.getMessage());
        }
    }

    /**
     * 编辑交易记录
     */
    @AutoLog(value = "半成品销售订单交易记录-编辑")
    @ApiOperation(value = "半成品销售订单交易记录-编辑", notes = "半成品销售订单交易记录-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody SemiProductSalesOrderTransaction transaction) {
        try {
            boolean result = transactionService.updateTransaction(transaction);
            if (result) {
                return Result.OK("编辑成功!");
            } else {
                return Result.error("编辑失败!");
            }
        } catch (Exception e) {
            log.error("编辑交易记录失败", e);
            return Result.error("编辑失败：" + e.getMessage());
        }
    }

    /**
     * 通过id删除
     */
    @AutoLog(value = "半成品销售订单交易记录-通过id删除")
    @ApiOperation(value = "半成品销售订单交易记录-通过id删除", notes = "半成品销售订单交易记录-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        try {
            boolean result = transactionService.deleteTransaction(id);
            if (result) {
                return Result.OK("删除成功!");
            } else {
                return Result.error("删除失败!");
            }
        } catch (Exception e) {
            log.error("删除交易记录失败", e);
            return Result.error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 批量删除
     */
    @AutoLog(value = "半成品销售订单交易记录-批量删除")
    @ApiOperation(value = "半成品销售订单交易记录-批量删除", notes = "半成品销售订单交易记录-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        try {
            String[] idArray = ids.split(",");
            for (String id : idArray) {
                if (oConvertUtils.isNotEmpty(id)) {
                    transactionService.deleteTransaction(id);
                }
            }
            return Result.OK("批量删除成功!");
        } catch (Exception e) {
            log.error("批量删除交易记录失败", e);
            return Result.error("批量删除失败：" + e.getMessage());
        }
    }

    /**
     * 通过id查询
     */
    @AutoLog(value = "半成品销售订单交易记录-通过id查询")
    @ApiOperation(value = "半成品销售订单交易记录-通过id查询", notes = "半成品销售订单交易记录-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<SemiProductSalesOrderTransaction> queryById(@RequestParam(name = "id", required = true) String id) {
        SemiProductSalesOrderTransaction transaction = transactionService.getById(id);
        if (transaction == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(transaction);
    }

    /**
     * 处理付款
     */
    @AutoLog(value = "半成品销售订单交易记录-处理付款")
    @ApiOperation(value = "半成品销售订单交易记录-处理付款", notes = "半成品销售订单交易记录-处理付款")
    @PostMapping(value = "/processPayment")
    public Result<String> processPayment(@RequestParam(name = "orderId", required = true) String orderId,
                                        @RequestParam(name = "amount", required = true) BigDecimal amount,
                                        @RequestParam(name = "transactionType", required = true) Integer transactionType,
                                        @RequestParam(name = "paymentMethod", required = true) Integer paymentMethod,
                                        @RequestParam(name = "description", required = false) String description,
                                        @RequestParam(name = "voucher", required = false) String voucher) {
        try {
            LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            String transactionPersonId = loginUser != null ? loginUser.getId() : null;
            
            boolean result = transactionService.processPayment(orderId, amount, transactionType, 
                paymentMethod, transactionPersonId, description, voucher);
            if (result) {
                return Result.OK("付款处理成功!");
            } else {
                return Result.error("付款处理失败!");
            }
        } catch (Exception e) {
            log.error("处理付款失败", e);
            return Result.error("付款处理失败：" + e.getMessage());
        }
    }

    /**
     * 处理退款
     */
    @AutoLog(value = "半成品销售订单交易记录-处理退款")
    @ApiOperation(value = "半成品销售订单交易记录-处理退款", notes = "半成品销售订单交易记录-处理退款")
    @PostMapping(value = "/processRefund")
    public Result<String> processRefund(@RequestParam(name = "orderId", required = true) String orderId,
                                       @RequestParam(name = "amount", required = true) BigDecimal amount,
                                       @RequestParam(name = "description", required = false) String description,
                                       @RequestParam(name = "reason", required = false) String reason) {
        try {
            LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            String transactionPersonId = loginUser != null ? loginUser.getId() : null;
            
            boolean result = transactionService.processRefund(orderId, amount, transactionPersonId, description, reason);
            if (result) {
                return Result.OK("退款处理成功!");
            } else {
                return Result.error("退款处理失败!");
            }
        } catch (Exception e) {
            log.error("处理退款失败", e);
            return Result.error("退款处理失败：" + e.getMessage());
        }
    }

    /**
     * 计算订单已付金额
     */
    @AutoLog(value = "半成品销售订单交易记录-计算已付金额")
    @ApiOperation(value = "半成品销售订单交易记录-计算已付金额", notes = "半成品销售订单交易记录-计算已付金额")
    @GetMapping(value = "/calculatePaidAmount")
    public Result<BigDecimal> calculatePaidAmount(@RequestParam(name = "orderId", required = true) String orderId) {
        try {
            BigDecimal paidAmount = transactionService.calculatePaidAmount(orderId);
            return Result.OK(paidAmount);
        } catch (Exception e) {
            log.error("计算已付金额失败", e);
            return Result.error("计算失败：" + e.getMessage());
        }
    }

    /**
     * 计算订单预付款金额
     */
    @AutoLog(value = "半成品销售订单交易记录-计算预付款金额")
    @ApiOperation(value = "半成品销售订单交易记录-计算预付款金额", notes = "半成品销售订单交易记录-计算预付款金额")
    @GetMapping(value = "/calculatePrepaymentAmount")
    public Result<BigDecimal> calculatePrepaymentAmount(@RequestParam(name = "orderId", required = true) String orderId) {
        try {
            BigDecimal prepaymentAmount = transactionService.calculatePrepaymentAmount(orderId);
            return Result.OK(prepaymentAmount);
        } catch (Exception e) {
            log.error("计算预付款金额失败", e);
            return Result.error("计算失败：" + e.getMessage());
        }
    }

    /**
     * 根据交易类型查询记录
     */
    @AutoLog(value = "半成品销售订单交易记录-根据交易类型查询")
    @ApiOperation(value = "半成品销售订单交易记录-根据交易类型查询", notes = "半成品销售订单交易记录-根据交易类型查询")
    @GetMapping(value = "/getByTransactionType")
    public Result<List<SemiProductSalesOrderTransaction>> getByTransactionType(@RequestParam(name = "orderId", required = true) String orderId,
                                                                              @RequestParam(name = "transactionType", required = true) Integer transactionType) {
        try {
            List<SemiProductSalesOrderTransaction> transactions = transactionService.getByTransactionType(orderId, transactionType);
            return Result.OK(transactions);
        } catch (Exception e) {
            log.error("根据交易类型查询记录失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 导出excel
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, SemiProductSalesOrderTransaction transaction) {
        return super.exportXls(request, transaction, SemiProductSalesOrderTransaction.class, "半成品销售订单交易记录");
    }

    /**
     * 通过excel导入数据
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, SemiProductSalesOrderTransaction.class);
    }
}
